/**
 * 扫码
 */

import Taro, { Component } from '@tarojs/taro';
import { connect } from '@tarojs/redux';
import { parseUrlToJson } from '@/utils';

@connect(({ page_login }) => ({ ...page_login }))
class ScanCode extends Component {
    constructor(props) {
        super(props);
    }

    do(onlyFromCamera, scanType) {
        return Taro.scanCode({ onlyFromCamera, scanType }).then(
            ({ errMsg, path, rawData, result, scanType }) => {
                if (errMsg.toLocaleLowerCase() !== 'scancode:ok') {
                    return Promise.reject({
                        errMsg,
                        path,
                        rawData,
                        result,
                        scanType
                    });
                }
                let params = {};
                switch (scanType) {
                    case 'WX_CODE':
                        // 小程序码
                        const { scene } = parseUrlToJson(path);
                        return this.parseScene(scene);
                    case 'QR_CODE':
                        // 普通二维码
                        return this.parseCode(result);
                }
            }
        );
    }

    parseCode(url) {
        const params = parseUrlToJson(url);
        const { dispatch } = this.props;
        const qrcode = decodeURIComponent(params.scene || '');
        // 来源权重最高
        switch (params.from) {
            case 'repair':
            case 'noNet':
            case 'brochure':
                return dispatch({
                    type: '$router/reLaunch',
                    payload: {
                        url: 'pages/introduce/index'
                    }
                });
            case 'home':
                if (qrcode) {
                    return dispatch({
                        type: 'page_login/login'
                    })
                        .then(() => {
                            return dispatch({
                                type: 'common/bindMachine',
                                payload: {
                                    qrcode
                                }
                            });
                        })
                        .then(res => {
                            dispatch({
                                type: '$router/forward',
                                payload: {
                                    url: '/urinalysis/pages/purchase/index',
                                    query: {
                                        macID: qrcode.split('_')[0]
                                    }
                                }
                            });
                            return res;
                        });
                }
                break;
            case 'bindTempResult':
                dispatch({
                    type: '$router/forward',
                    payload: {
                        url: '/urinalysis/pages/scan/binding',
                        query: {
                            tempID: qrcode
                        }
                    }
                });
                return params;
        }

        // 路径权重
        if (params.path) {
            const url = decodeURIComponent(params.path);
            this._forward(`/${url}`);
            return {
                url,
                project: 'mm'
            };
        }

        return params;
    }

    parseScene(scene) {
        scene = decodeURIComponent(scene);
        const params = scene.split('$');
        if (params.length === 3) {
            const [deviceId, linkToken, lang] = params;
            deviceId &&
                this._forward('/pages/mgStart/index', {
                    deviceId,
                    linkToken,
                    lang
                });
            return {
                deviceId,
                linkToken,
                lang,
                project: 'mm'
            };
        } else {
            return params;
        }
    }

    _forward(url, query) {
        const { dispatch } = this.props;
        // 如果当前页面是同一页面替换跳转
        const pages = Taro.getCurrentPages();
        const len = pages.length;
        const currentPage = pages[len - 1].route;
        if (url.indexOf(currentPage) !== -1) {
            dispatch({
                type: '$router/redirect',
                payload: {
                    url,
                    query
                }
            });
        } else {
            dispatch({
                type: '$router/forward',
                payload: {
                    url,
                    query
                }
            });
        }
    }
}

let sc = new ScanCode();

// 处理微信扫一扫进入页面的逻辑
export function parseCode(url) {
    sc.parseCode(url);
}

export function parseScene(scene) {
    return sc.parseScene(scene);
}

export default function(onlyFromCamera = true, scanType) {
    return sc.do(onlyFromCamera, scanType);
}
